#include <iostream>
#include <string.h>
using std::cout;
using std::endl;

class Base
{
public:
    Base(long base = 1)
    : _base(base)
    {
        // cout << "Base(long)" << endl;
    }
protected:
    long _base;
};

class Derived
: public Base
{
public:
    Derived(long ba,long de, const char * pderived)
    : Base(ba)
    , _derived(de)
    , _pderived(new char[strlen(pderived) + 1]())
    {
        strcpy(_pderived, pderived);
    //     cout << "Derived(long,long)" << endl;
    }

    ~Derived(){
        if(_pderived != nullptr){
            delete[] _pderived;
            _pderived = nullptr; 
        }
    }

    Derived(const Derived & rhs)
    // const Base& 可以绑定Derived对象
    : Base(rhs) // 显示调用Base的拷贝构造，如果为Base(rhs._base)的话，则为有参构造，最好为拷贝构造，复制即可
    , _derived(rhs._derived)
    , _pderived(new char[strlen(rhs._pderived) + 1]())
    {
        strcpy(_pderived, rhs._pderived);
        cout << "Derived的拷贝构造" << endl;
    }

    Derived & operator=(const Derived& rhs){
        if (this != &rhs){
            cout << "子类的赋值运算符函数" << endl;
            Base::operator=(rhs); // 显式调用基类的赋值运算符函数，把基类子对象部分的成员也赋值过来
            delete [] _pderived;
            _pderived = new char[strlen(rhs._pderived) + 1]();
            strcpy(_pderived, rhs._pderived);
            _derived = rhs._derived;
        }
        return *this;
    }

    void print() const
    {
        cout << "_base:" << _base << endl;
        cout << "_derived:" << _derived << endl;
        cout << "_pderived:" << _pderived << endl;
    }
private:
    long _derived;
    char * _pderived;
};


void test0(){
    // cout << sizeof(long) << endl;
    // cout << sizeof(Base) << endl;
    // cout << sizeof(Derived) << endl;

    Derived d1(7, 8, "Beijing"); // 有参构造
    Derived d2 = d1; // 拷贝构造函数，编译器将其解释为Derived d2(d1);
    Derived d3(3, 5, "Shanghai"); // 拷贝构造函数
    d3 = d2;

    d1.print();
    d2.print();
    d3.print();
}

int main(void){
    test0();
    return 0;
}
